package cn.zglbk.generator.utils;
import cn.zglbk.generator.model.FileContentEntity;
import cn.zglbk.utils.Assert;
import org.apache.commons.configuration.Configuration;
import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 读取txt文本内容
 * @author zglbk.cn
 * @email 1030681978@qq.com
 * @date 2020/10/21 16:49
 */
class ReadFileUtils {
    static List<FileContentEntity> readFileByPath(){
        //配置信息
        List<FileContentEntity> outFile = new ArrayList<>();
        Configuration config = GenUtils.getConfig();
        File file = new File(config.getString("readPath"));
        read(file,outFile);
        return outFile;
    }
    private static void read(File file,List<FileContentEntity> outFile){
        if(!file.exists() || !file.isDirectory()){
            return;
        }
        File[] files = file.listFiles();
        for (File f : files) {
            if(f.isDirectory()){
                read(f,outFile);
            }else if(f.getName().endsWith(".txt")){
               outFile.add(readOneFileByPath(f));
            }
        }
    }
    private static FileContentEntity readOneFileByPath(File file){
        String content = "";
        try {
            content = FileUtils.readFileToString(file,"UTF-8");
        } catch (IOException e) {
            e.printStackTrace();
        }
        FileContentEntity entity = fileContentAnalysis(content);
        entity.setTableName(file.getName());
        entity.setClassName(file.getName().replace(".txt",""));
        return entity;
    }
    private static FileContentEntity fileContentAnalysis(String content){
        String[] split = org.apache.commons.lang.StringUtils.split(content, "\r\n");

        Assert.isEmptyArr(split,new FsyException("配置文件内容格式不符合要求"));
        Assert.isTrue(split.length < 3,new FsyException("配置文件内容格式不符合要求"));

        FileContentEntity entity = new FileContentEntity();
        entity.setAttrNames(split[0].split("\t",-1));
        entity.setAttrTypes(split[1].split("\t",-1));
        entity.setCommons(split[2].split("\t",-1));
        //数据对应关系是否一致
        Assert.isEmptyArr(entity.getAttrNames(),new FsyException("配置文件内容格式不符合要求"));
        //数据对应关系是否一致
        Assert.unlikeArrLen(entity.getAttrNames(),entity.getAttrTypes(),new FsyException("配置文件内容格式不符合要求"));
        Assert.unlikeArrLen(entity.getAttrNames(),entity.getCommons(),new FsyException("配置文件内容格式不符合要求"));
        return entity;
    }
}
